# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

import datetime
import logging
import json
import sys

from tornado.ioloop import IOLoop

from coin.base.config import Config
from coin.exchange.base.order_gateway import OrderSide
from coin.exchange.bithumb.order_gateway import BithumbOrderGateway
from coin.exchange.bithumb.kr_rest.product import BithumbProduct
from coin.exchange.bithumb.kr_rest.currency import BithumbCurrency
from coin.flow.simple_queue import SimpleQueue


def print_working_order(ioloop, og):
  if og.get_working_order():
    print('Working orders:')
    for order in og.get_working_order():
      print('  %s' % str(order))
  else:
    print('No working order')
  ioloop.add_timeout(datetime.timedelta(seconds=5), print_working_order, ioloop, og)


def print_balance(ioloop, og):
  balances = og.get_balances()
  print('Balances:')
  print(json.dumps(balances, indent=2))
  ioloop.add_timeout(datetime.timedelta(seconds=5), print_balance, ioloop, og)


def submit_test_order(og, product):
  og.submit(product, 3000, 1, OrderSide.BUY)


def cancel_test_order(og):
  og.cancel_all()


def main(argv):
  ioloop = IOLoop.current()
  product = BithumbProduct.FromStr('QTUM-KRW')
  currency = BithumbCurrency.FromCurrency(product.base)
  og = BithumbOrderGateway(Config.from_config_filename(filename='bithumb_pilot01'), [currency],
                           product)
  queue = SimpleQueue('test')
  og.start(queue, ioloop)
  ioloop.add_timeout(datetime.timedelta(seconds=5), print_working_order, ioloop, og)
  ioloop.add_timeout(datetime.timedelta(seconds=5), print_balance, ioloop, og)
  # ioloop.add_timeout(datetime.timedelta(seconds=5), submit_test_order, og, product)
  # ioloop.add_timeout(datetime.timedelta(seconds=10), cancel_test_order, og)
  ioloop.start()
  return 0


if __name__ == '__main__':
  logging.basicConfig(level='INFO', format='%(levelname)s %(asctime)s %(name)s] %(message)s')
  sys.exit(main(sys.argv))
